package com.bw.module_mine

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.bw.lib_common.base.BaseMVIFragment
import com.bw.lib_common.livedata_eventbus.Events
import com.bw.lib_common.livedata_eventbus.LiveDataEventBus
import com.bw.lib_common.livedata_eventbuss.LiveEventBus
import com.bw.lib_common.utils.ToastUtils
import com.bw.lib_image.ImageBindingAdapter
import com.bw.lib_storage.UserMMKV
import com.bw.lib_storage.db.DBUtils
import com.bw.lib_storage.db.entity.History
import com.bw.module_mine.databinding.FragmentMineBinding
import com.bw.module_mine.intent.MineIntent
import com.bw.module_mine.model.Adpter.HistoryAdapter
import com.bw.module_mine.state.AccountState
import com.bw.module_mine.viewmodel.MineViewModel
import com.bw.module_mine.HistoryListActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

@AndroidEntryPoint
class MineFragment : BaseMVIFragment() {
    private val binding : FragmentMineBinding by lazy {
        FragmentMineBinding.inflate(layoutInflater)
    }
    
    // 加载历史记录
    private fun loadHistoryRecords() {
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                val historyList = DBUtils.getDB().historyDao().getAllHistory()
                    .toMutableList()
                    .apply { reverse() } // 最新的在前面
                
                withContext(Dispatchers.Main) {
                    historyAdapter = HistoryAdapter(requireContext(), historyList)
                    binding.rvHistory.adapter = historyAdapter
                    
                    // 设置点击事件
                    historyAdapter.setOnItemClickListener(object : HistoryAdapter.OnItemClickListener {
                        override fun onItemClick(history: History) {
                            // 这里可以跳转到视频播放页面，传入视频路径
                            val intent = Intent()
                            intent.putExtra("videoPath", history.content)
                            intent.putExtra("title", history.title)
                            startActivity(intent)
                        }
                    })
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // 设置RecyclerView
        binding.rvHistory.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        
        // 加载历史记录
        loadHistoryRecords()
        
        // "全部"按钮点击事件
//        val textView = binding.tvHistory.findViewById<TextView>(R.id.textView)
//        if (textView != null) {
//            textView.setOnClickListener {
//                val intent = Intent(requireContext(), HistoryListActivity::class.java)
//                startActivity(intent)
//            }

        //  去历史记录页面
           binding.tvHistory.setOnClickListener {
               startActivity(Intent(requireContext(),HistoryListActivity::class.java))
           }
    }
    
    override fun onResume() {
        super.onResume()
        // 每次页面显示时重新加载历史记录
        loadHistoryRecords()
    }
    private lateinit var mViewModel:MineViewModel
    private lateinit var historyAdapter: HistoryAdapter
    
    // LiveEventBus观察者，用于接收登录成功的通知
    private val loginSuccessObserver = { _: Boolean ->
        // 登录成功，刷新UI
        refreshUserData()
    }
    override fun generateViewModel() {
        mViewModel = ViewModelProvider(this)[MineViewModel::class.java]
    }
    override fun getFragmentRootView(): View {
        return binding.root
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                mViewModel.AccountState_.collect(){
                    when(it) {
                        is AccountState.Success -> {
                            binding.viewModel = it.data
                            Log.d("MineFragment", "Success: ${it.data}")
                        }
                        is AccountState.Loading -> {

                        }
                        is AccountState.Init -> {

                        }
                        is AccountState.Error -> {

                        }
                        is AccountState.Empty -> {

                        }
                    }
                }
            }
        }

    }

    override fun initData() {
        super.initData()
        LiveEventBus.with<Boolean>(Events.EVENT_LOGOUT,true)
            .observe(this){
                refreshUserData()
            }

        // 监听红包事件
        LiveEventBus.with<Boolean>(Events.EVENT_RED_PACKET)
            .observeSticky(this) {
                getAccount(UserMMKV.accountId.toInt())

//                lifecycleScope.launch {
//                    repeatOnLifecycle(Lifecycle.State.RESUMED) {
//                        mViewModel.intents.send(MineIntent.GetAccount(id))
//                    }
//                }
            }

    }

    override fun initView() {
        super.initView()
        updateUIByLoginState()
        
        // 初始化数据库
        DBUtils.init(requireContext(), "club.db")
        
        // 注册LiveEventBus观察者
        LiveEventBus.with<Boolean>(Events.EVENT_LOGIN_SUCCESS).observe(this) {
            loginSuccessObserver(it)
        }
    }
    
    // 根据登录状态更新UI
    private fun updateUIByLoginState() {
        if (UserMMKV.token.isNullOrEmpty()){
            binding.constraintLayout.visibility = View.INVISIBLE
            binding.tvGoLogin.visibility = View.VISIBLE
        }else{
            binding.constraintLayout.visibility = View.VISIBLE
            binding.tvGoLogin.visibility = View.INVISIBLE
            
            // 获取用户信息
            val userId = UserMMKV.accountId.toInt()
            if (userId != 0) {
                getAccount(userId)
            }
            
            // 设置用户名
            if (!UserMMKV.userName.isNullOrEmpty()) {
                binding.tvUser.text = UserMMKV.userName
            }
            
            // 设置用户头像
            val imageUrl = UserMMKV.image
            if (imageUrl.isNotEmpty() && imageUrl != "null") {
                try {
                    // 使用Glide加载头像，设置为圆形
                    ImageBindingAdapter.avatarUrl(binding.ivUser,imageUrl)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            } else {
                // 设置默认头像
                binding.ivUser.setImageResource(com.bw.lib_image.R.mipmap.iv_default_user)
            }


        }
    }
    
    // 刷新用户数据
    private fun refreshUserData() {
        updateUIByLoginState()
    }

    private fun getAccount(id:Int) {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                mViewModel.intents.send(MineIntent.GetAccount(id))
            }
        }
    }

    private fun checkLogin(): Boolean {
    if (UserMMKV.token.isNullOrEmpty()) {
        ToastUtils.showLong(requireContext(), "还没有登录")
        return false
    }
    return true
}

    override fun initEvent() {
        super.initEvent()
        
        // 登录按钮点击事件
        binding.tvGoLogin.setOnClickListener {
            //ToastUtils.showLong(requireContext(),"askhfdak")
//            ARouter.getInstance().build("/mine/LoginActivity").navigation()
            startActivity(Intent(requireContext(),LoginActivity::class.java))
        }

        binding.llCollection.setOnClickListener {
            if (!checkLogin()) return@setOnClickListener
            ARouter.getInstance().build("/mine/MyCollectionsActivity").navigation()
        }

        binding.tvGoWithdraw.setOnClickListener {
            if (!checkLogin()) return@setOnClickListener
            ARouter.getInstance().build("/mine/WithdrawMoneyActivity").navigation()
        }

        binding.ivUser.setOnClickListener {
            LogoutDialog(
                title = "温馨提示",
                message = "是否确定退出登录？",
                confirmText = "确定",
                cancelText = "取消",
                cancelable = true,
                onCancelClick = {

                },
                onConfirmClick = {
                    ToastUtils.showLong(context,"退出了")
                    UserMMKV.mmkv.clearAll()
                    LiveEventBus.with<Boolean>(Events.EVENT_LOGOUT).post(true)
                },
                onlyConfirmButton = false
            ).show(requireActivity().supportFragmentManager)
        }
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        // 使用LiveEventBus后无需手动注销广播接收器
    }


}